from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from core.models.daily_attendance import DailyAttendance
from core.models.homework_submission import HomeworkSubmission
from core.models.honor import HonorRecord
from core.models.leave_request import LeaveRequest
from core.models.student import Student
from core.models.homework import Homework
from django.db.models import Avg
from django.utils import timezone
from core.models.class_subject_assignment import ClassSubjectAssignment
from core.views.utils import get_classes
from core.models.discipline import DisciplineRecord
from core.models.discipline import DisciplineType
@login_required
# 获取学生在校表现情况的视图函数
def student_performance(request, student_id,strdate):
    """
    根据学生的考勤和作业上交情况，生成学生在校表现情况。
    :param strdate: 日期字符串
    :param request: 请求对象
    :param student_id: 学生 ID
    :return: 渲染后的学生在校表现页面
    """
    try:
        #根据student_id得到student实例
        student = Student.objects.filter(id=student_id).first()
        # 转换日期字符串为日期对象
        date = timezone.datetime.strptime(strdate, '%Y-%m-%d').date()
        # 获取今日的考勤数据
        attendance_records = DailyAttendance.objects.filter(student=student, date=date).first()
        # print("attendance_records",attendance_records)

        # 获取今日的作业数据
        # 获取学生对应的User实例（假设Student模型有user外键，若没有需调整逻辑）
        # 示例：若Student与User通过OneToOne关联，使用student.user
        # 若当前用户是班主任，使用request.user
        # 此处假设通过其他方式获取正确的User实例（如班主任）
        # 实际需根据业务逻辑调整
        teacher_user = student.classes.first().homeroom_teacher  # 示例：获取学生所在班级的班主任User实例
        classes=get_classes(teacher_user)
       
        assignments = ClassSubjectAssignment.objects.filter(class_id__in=classes)
        # 提取学科名称
        subjects = [assignment.subject.name for assignment in assignments]
        homework_submissions=[]
        for subject in subjects:
            #根据学科和截至时间得到所有的老师布置的作业
            homeworks=Homework.objects.filter(class_subject__subject__name=subject,due_date__lte=date)
            Homeworks = HomeworkSubmission.objects.filter(
                homework__in=homeworks,
                student_id=student_id
            )
            homework_submissions.extend(Homeworks)
       

        #查询今日请假
        leave_days=LeaveRequest.objects.filter(student=student, start_date=strdate)
        print(leave_days)
        #今日违纪
        today_discipline = DisciplineRecord.objects.filter(student=student,happened_at=strdate,discipline_type__in=DisciplineType.objects.all())
        print(today_discipline)
        today_honor=HonorRecord.objects.filter(student=student,award_date=strdate)
        # # 生成综合表现评价
        # if attendance_score > 90 and submission_rate > 90:
        #     performance = '优秀'
        # elif attendance_score > 80 and submission_rate > 80:
        #     performance = '良好'
        # elif attendance_score > 70 and submission_rate > 70:
        #     performance = '中等'
        # else:
        #     performance = '有待提高'

        context = {
            'student': student,
            'attendance_records': attendance_records,
            'homework_submissions': homework_submissions,
            'leave_days':leave_days,
            'today_discipline':today_discipline,
            'today_honor':today_honor,
        }

        return render(request, 'classmanage/student_performance.html', context)
    except Student.DoesNotExist:
        return render(request, '404.html', {'message': '未找到该学生信息'})